/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("table_wgjy",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Text.Json;
using DGZImp.Core.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ATkg.BizAppProject.Models;
using DGZImp.Core.EFDbContext;
using DGZImp.Core.DbSqlSugar;

namespace ATkg.BizAppProject.Controllers
{
    public partial class table_wgjyController

    {
        
        //public string url = "http://10.7.1.3/jsonrpc";
        //public string db = "atm";
        //public string userName = "fenkuxt@atmcn.com";
        //public string password = "fen12345";
        private readonly Itable_wgjyService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;

        [ActivatorUtilitiesConstructor]
        public table_wgjyController(
            Itable_wgjyService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        

        [HttpPost("SyncProductionTask_wgjy_post")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> SyncProductionTask_wgjy_post([FromBody] PageDataOptionsWgjy order_no_)

        {
            Console.WriteLine("post方法调用");
            string order_no = order_no_.name_order?.ToString()?.Trim();
            var r = await Service.SyncProductionTask_wgjy(order_no);
            return JsonNormal(r);
        }

        [HttpGet("SyncProductionTask_wgjy_get")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> SyncProductionTask_wgjy_get(string name_order)
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {
            Console.WriteLine("get方法调用");
            var r = await Service.SyncProductionTask_wgjy(name_order);

            //var r = 0;
            return JsonNormal(r);
        }

        [HttpGet("SyncProductionTask_wgjy_get_pg")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> SyncProductionTask_wgjy_get_pg(string name_order, string mes_data)
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {
            Console.WriteLine("get方法调用_品管上传MES");
            //object data_test = mes_data;
            //using JsonDocument document = JsonDocument.Parse(mes_data);
            //JsonElement root = document.RootElement;
            //Console.WriteLine(root);
            //Console.WriteLine(root.GetProperty("defect_plating_disability_final_qty"));
            ////Person person = JsonConvert.DeserializeObject<Person>(mes_data);
            //Console.WriteLine(root.GetProperty("inspection_time"));


            JObject mes_data_final = JObject.Parse(mes_data);
            Console.WriteLine(mes_data_final);
            Console.WriteLine(mes_data_final["defect_plating_disability_final_qty"]);
            Console.WriteLine(mes_data_final["inspection_time"]);



            Console.WriteLine(mes_data);
            var r = await Service.SyncProductionTask_wgjy_pg(name_order, mes_data_final);
            //var r = JsonNormal("1");

            //var r = 0;
            return JsonNormal(r);
        }

        [HttpGet("gzd_search")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> gzd_search(string name_order)
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {
            Console.WriteLine("get方法调用");
            var r = await Service.gzd_search_task(name_order);

            //var r = 0;
            return JsonNormal(r);
        }

        [HttpGet("get_cailiao_plan_steel")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> get_cailiao_plan_steel()
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {
            Console.WriteLine("get方法调用");
            var r = await Service.Sync_cailiao_plan_data();

            //var r = 0;
            return JsonNormal(r);
        }





        public class Item
        {
            [System.Text.Json.Serialization.JsonPropertyName("序号")]
            public int SerialNumber { get; set; }

            [System.Text.Json.Serialization.JsonPropertyName("内容")]
            public string Content { get; set; }
        }

        [HttpGet("gzd_data_deal")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> gzd_data_deal(string name_order, string order_id,string gzd_data, string mes_old_data_id)
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {
            Console.WriteLine("get方法调用111111111");
            Console.WriteLine(gzd_data);
            Console.WriteLine(gzd_data);
            string[] stringArray = gzd_data.Split(',');
            float[] floatArray = new float[stringArray.Length];

            for (int i = 0; i < stringArray.Length; i++)
            {
                if (float.TryParse(stringArray[i], out float result))
                {
                    floatArray[i] = result;
                }
                else
                {
                    Console.WriteLine($"无法将 {stringArray[i]} 转换为整数。");
                }
            }

            foreach (float item in floatArray)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine(floatArray[0]);
            Console.WriteLine(mes_old_data_id);
            Console.WriteLine("LLLL");



            Console.WriteLine(mes_old_data_id);
            string[] stringArray_ = mes_old_data_id.Split(',');
            int[] intArray = new int[stringArray_.Length];

            for (int i = 0; i < stringArray_.Length; i++)
            {
                if (int.TryParse(stringArray_[i], out int result))
                {
                    intArray[i] = result;
                }
                else
                {
                    Console.WriteLine($"无法将 {stringArray_[i]} 转换为整数。");
                }
            }

            foreach (float item in intArray)
            {
                Console.WriteLine(item);
            }

            //string order_no1 = gzd_data.ToJson();
            //Console.WriteLine(order_no1);
            var r = await Service.gzd_upmes_excel_task(name_order, order_id, floatArray, intArray);

            //var r = 0;
            return JsonNormal(r);
        }

        [HttpGet("save_data_deal")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> save_data_deal(string name_order, string lot_name, string gzd_data, string formattedTime, 
            string path_file_mode, string formattedTime_ymd, string test_modle)
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {
            Console.WriteLine("get方法调用save");
            Console.WriteLine(gzd_data);
            Console.WriteLine(gzd_data);
            string[] stringArray = gzd_data.Split(',');
            float[] floatArray = new float[stringArray.Length];

            for (int i = 0; i < stringArray.Length; i++)
            {
                if (float.TryParse(stringArray[i], out float result))
                {
                    floatArray[i] = result;
                }
                else
                {
                    Console.WriteLine($"无法将 {stringArray[i]} 转换为整数。");
                }
            }

            foreach (float item in floatArray)
            {
                Console.WriteLine(item);
            }

            var r = await Service.save_excel_task(name_order, lot_name, floatArray, formattedTime, path_file_mode, formattedTime_ymd, test_modle);

            //var r = 0;
            Console.Write("返回的结果: ");
            Console.WriteLine(r);
            return JsonNormal(r);
        }
        public class test_pg_nk
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string TestName { get; set; }
            public string Lot { get; set; }
            public string TestData { get; set; }
            public string TestPerson { get; set; }
            public string TestTime { get; set; }
            public string isUploaded { get; set; }

        }
        [HttpGet("search_data_jiance1")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<object> search_data_jiance1()
        {

            var result = Db.Queryable<test_pg_nk>()  //                      
                    .Select(m => new
                    {
                        m.TestName,
                        m.Lot,
                        m.TestData,
                        m.TestPerson,
                        m.TestTime,
                        m.isUploaded
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
            return result;
        }

        [HttpPost("insert_db_info")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<object> InsertDbInfo([FromBody] List<test_pg_nk> mesData)
        {
            Console.WriteLine("FFFFF");

            // 验证是否成功接收数据
            if (mesData == null || mesData.Count == 0)
            {
                Console.WriteLine("未接收到有效数据");
                return new { success = false, message = "未接收到数据" };
            }

            // 遍历接收的数据（示例）
            var list_insert_db = new List<test_pg_nk>();
            foreach (var data in mesData)
            {
                Console.WriteLine($"测试项：{data.TestName}，批次：{data.Lot}，结果：{data.TestData}");
                var data_3 = new test_pg_nk
                {
                    TestName = data.TestName,
                    Lot = data.Lot,
                    TestData = data.TestData,
                    TestPerson = data.TestPerson,
                    TestTime = data.TestTime,
                    isUploaded = data.isUploaded,
                };
                list_insert_db.Add(data_3);
                
            }
            await Db.DoInsertAsync<test_pg_nk>(list_insert_db);


            // 后续业务逻辑（例如批量插入数据库）
            // 示例：批量插入到test_pg_nk表（假设你的Db框架支持批量操作）
            // var insertResult = await Db.Insertable(mesData).ExecuteCommandAsync();

            return new { success = true, receivedCount = mesData.Count, data = mesData };
        }


        [HttpGet("up_to_mes_jiance1")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<object> up_to_mes_jiance1()
        {

            //var result = Db.Queryable<test_pg_nk>()  //                      
            //        .Select(m => new
            //        {
            //            m.TestName,
            //            m.Lot,
            //            m.TestData,
            //            m.TestPerson,
            //            m.TestTime,
            //        })               // 选择 update_data 字段
            //        .ToList();                               // 执行查询并返回列表
            var result = await Service.up_to_mes_();
            return result;
        }

    }
}
